import socket
import time

def red_Light_on():
    try:
        with open('/proc/gpio/gpio3','w') as open_red_light:

            open_red_light.write("1")

    except IOError as e:

        print(f'Failed to write to /proc/gpio/gpio3: {e}')

        red_Light_on()

def red_light_off():
    try:
        with open('/proc/gpio/gpio3','w') as open_red_light:

            open_red_light.write("0")

    except IOError as e:

        print(f'Failed to write to /proc/gpio/gpio3: {e}')

        red_light_off()    

def blue_Light_on():
    try:
        with open('/proc/gpio/gpio2','w') as open_blue_light:

            open_blue_light.write("1")

    except IOError as e:

        print(f'Failed to write to /proc/gpio/gpio2: {e}')

        blue_Light_on()

def blue_Light_off():
    try:
        with open('/proc/gpio/gpio2','w') as open_blue_light:

            open_blue_light.write("0")

    except IOError as e:

        print(f'Failed to write to /proc/gpio/gpio2: {e}')

        blue_Light_off()

def check_device(ip_address, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(2)  # 设置超时时间为2秒

        result = sock.connect_ex((ip_address, port))

        if result == 0:
            return True  # 端口开放，设备存在
        else:
            return False  # 端口关闭，设备不存在

    except Exception as e:
        print("发生错误：" + str(e))
        return False  # 发生异常，设备不存在

if __name__ == '__main__':
        
    from auto_ip import get_network_info

    while True:

        network_info = get_network_info()

        if network_info == None:

            time.sleep(5)

            continue

        ip_address = network_info["gateway"]

        port = 80

        device_exists = check_device(ip_address, port)

        blue_Light_off()
        red_light_off()

        print(device_exists)

        if device_exists:
            blue_Light_on()
        else:
            red_Light_on()
    
        time.sleep(5)
